package com.class04.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;


import javax.sql.DataSource;

/**
 * @ClassDescription:
 * 持久层配置类：连接池，sqlSessionFactory，sqlSession，Mapper代理对象
 * todo 如果将dataSource和mybatis的组件配置到一起，引发@Value注解不生效的问题
 *  原因：mybatis的组件优先加载，@value还没有读取！
 *  解决：分开配置，写到不同的类即可
 *
 * 方式1.保留外部配置文件的方式
 * @JdkVersion: 17
 * @Author: yxy
 * @Created: 2023/12/21 10:35
 */
@Configuration
public class MapperJavaConfig {
    @Bean
    public SqlSessionFactoryBean sessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //指定配置文件等信息
        //指定数据库连接池对象
        sqlSessionFactoryBean.setDataSource(dataSource);
//       指定外部的mybatis外部的
        Resource resource = new ClassPathResource("mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(resource);
        return sqlSessionFactoryBean;
    }
    //mapper代理对象加入ioc
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
//        mapper代理对应的factoryBean->指定一个包->mapper接口
//        ->sqlSessionFactory->sqlSession->getMapper->mapper代理对象 ->ioc
        MapperScannerConfigurer mapperScannerConfigurer =
                new MapperScannerConfigurer();
        //mapper接口和mapper.xml编译之后所在共同包
        mapperScannerConfigurer.setBasePackage("com.class04.mapper");
        return mapperScannerConfigurer;
    }
}
